#include "lineedit.h"
#include <QCoreApplication>
#include <QMouseEvent>

namespace yc {

LineEdit::LineEdit(QWidget* parent) : QLineEdit(parent)
{
    setContextMenuPolicy(Qt::NoContextMenu);
}

LineEdit::LineEdit(const QString& text, QWidget* parent) : QLineEdit(text, parent)
{
    setContextMenuPolicy(Qt::NoContextMenu);
}

void LineEdit::setAutoClearFocus(bool auto_clear_focus)
{
    if (auto_clear_focus_ != auto_clear_focus) {
        auto_clear_focus_ = auto_clear_focus;
        if (auto_clear_focus) {
            QCoreApplication::instance()->installEventFilter(this);
        } else {
            QCoreApplication::instance()->removeEventFilter(this);
        }
    }
}

bool LineEdit::eventFilter(QObject* watched, QEvent* event)
{
    if (event->type() == QEvent::MouseButtonPress) {
        QMouseEvent* me = static_cast<QMouseEvent*>(event);
        if (auto_clear_focus_
            && !contentsRect().contains(mapFromGlobal(me->globalPosition().toPoint()))) {
            clearFocus();
        }
    }
    return QLineEdit::eventFilter(watched, event);
}

void LineEdit::focusInEvent(QFocusEvent* event)
{
    QLineEdit::focusInEvent(event);
    Q_EMIT focusedIn();
}

void LineEdit::focusOutEvent(QFocusEvent* event)
{
    QLineEdit::focusOutEvent(event);
    Q_EMIT focusedOut();
    Q_EMIT editingFinished();
}
} // namespace yc
